package com.atguigu.gmall.realtime.app.dwd;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.realtime.app.BaseApp;
import com.atguigu.gmall.realtime.util.MyKafkaUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple3;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

import java.time.Duration;
import java.util.ArrayList;
import java.util.Comparator;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/3/15 9:32
 */
public class DWDLogApp extends BaseApp {
    public static void main(String[] args) {
        new DWDLogApp().init(10000, 2, "DWDLogApp", "DWDLogApp", "ods_log");
    }
    
    @Override
    public void run(StreamExecutionEnvironment env,
                    DataStreamSource<String> sourceStream) {
        // 1. 区别新老客户
        final SingleOutputStreamOperator<JSONObject> validateFlatDS = distinguishNewOrOld(sourceStream);
        // 2. 分流: 把一个流变成多个流   启动日志在主流, 其他的日志在测输出流
        // f0: 启动 f1: 页面 f2: 曝光
        final Tuple3<DataStream<JSONObject>, DataStream<JSONObject>, DataStream<JSONObject>> streams = splitSteam(validateFlatDS);
        // 3. 分流后的数据写入到DWD层(Kafka)
        sendToKafka(streams);
    }
    
    private void sendToKafka(Tuple3<DataStream<JSONObject>, DataStream<JSONObject>, DataStream<JSONObject>> streams) {
        streams.f0.map(obj -> JSON.toJSONString(obj)).addSink(MyKafkaUtil.getFlinkKafkaSink("dwd_start_log")).setParallelism(1);
        streams.f1.map(obj -> {
            final String pageId = obj.getJSONObject("page").getString("page_id");
            if("good_list".equalsIgnoreCase(pageId)){
                System.out.println(obj);
            }
            return JSON.toJSONString(obj);
        }).addSink(MyKafkaUtil.getFlinkKafkaSink("dwd_page_log")).setParallelism(1);
        streams.f2.map(obj -> JSON.toJSONString(obj)).addSink(MyKafkaUtil.getFlinkKafkaSink("dwd_display_log")).setParallelism(1);
    }
    
    // 对流进行分流
    private Tuple3<DataStream<JSONObject>, DataStream<JSONObject>, DataStream<JSONObject>> splitSteam(SingleOutputStreamOperator<JSONObject> validateFlatDS) {
        
        final OutputTag<JSONObject> pageTag = new OutputTag<JSONObject>("page") {};
        final OutputTag<JSONObject> displayTag = new OutputTag<JSONObject>("display") {};
        
        final SingleOutputStreamOperator<JSONObject> startupStream = validateFlatDS
            .process(new ProcessFunction<JSONObject, JSONObject>() {
                @Override
                public void processElement(JSONObject value,
                                           Context ctx,
                                           Collector<JSONObject> out) throws Exception {
                    
                    final JSONObject startObj = value.getJSONObject("start");
                    if (startObj != null) {
                        // 这条日志是启动日志
                        out.collect(value);
                    } else {
                        final JSONObject pageObj = value.getJSONObject("page");
                        if (pageObj != null) {
                            ctx.output(pageTag, value);
                        }
                        
                        final JSONArray displaysArr = value.getJSONArray("displays");
                        if (displaysArr != null && displaysArr.size() > 0) {
                            for (int i = 0; i < displaysArr.size(); i++) {
                                final JSONObject displayObj = displaysArr.getJSONObject(i);
                                final String pageId = value.getJSONObject("page").getString("page_id");
                                displayObj.put("page_id", pageId);
                                displayObj.put("ts", value.getLong("ts"));
                                ctx.output(displayTag, displayObj);
                            }
                        }
                    }
                }
            });
        
        return Tuple3.of(startupStream,
                         startupStream.getSideOutput(pageTag),
                         startupStream.getSideOutput(displayTag));
        
    }
    
    // 区别新老客户
    private SingleOutputStreamOperator<JSONObject> distinguishNewOrOld(DataStreamSource<String> sourceStream) {
        final SingleOutputStreamOperator<JSONObject> result = sourceStream
            .map(JSON::parseObject)
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(1))
                    .withTimestampAssigner((obj, ts) -> obj.getLong("ts"))
            )
            .keyBy(new KeySelector<JSONObject, String>() {
                @Override
                public String getKey(JSONObject value) throws Exception {
                    return value.getJSONObject("common").getString("mid");
                }
            })
            .window(TumblingEventTimeWindows.of(Time.seconds(5)))
            .process(new ProcessWindowFunction<JSONObject, JSONObject, String, TimeWindow>() {
                
                private ValueState<Long> firstVisitState;
                
                @Override
                public void open(Configuration parameters) throws Exception {
                    firstVisitState = getRuntimeContext()
                        .getState(new ValueStateDescriptor<Long>("firstVisitState", Long.class));
                    
                }
                
                @Override
                public void process(String key,
                                    Context context,
                                    Iterable<JSONObject> elements,
                                    Collector<JSONObject> out) throws Exception {
                    // 每条数据判断是否为新老用户
                    if (firstVisitState.value() == null) {
                        // 1. 这是这个mid的第一个窗口, 按照时间戳排序, 然后把第一个标记为新用户, 其他都是旧用户
                        final ArrayList<JSONObject> list = new ArrayList<>();
                        for (JSONObject ele : elements) {
                            list.add(ele);
                        }
                        list.sort(Comparator.comparing(o -> o.getLong("ts")));
                        
                        for (int i = 0; i < list.size(); i++) {
                            if (i == 0) {
                                list.get(i).getJSONObject("common").put("is_new", "1");
                                firstVisitState.update(list.get(i).getLong("ts")); // 更新状态
                            } else {
                                list.get(i).getJSONObject("common").put("is_new", "0");
                            }
                            out.collect(list.get(i));
                        }
                    } else {
                        // 不是这个mid的第一个窗口, 所有的数据都是老用户访问
                        for (JSONObject obj : elements) {
                            obj.getJSONObject("common").put("is_new", "0");
                            out.collect(obj);
                        }
                    }
                }
            });
        return result;
    }
    
}
